package com.system.base.pay;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPay;
import com.system.anno.PayTemplate;
import com.system.base.ApiResult;
import com.system.config.NBCBConfig;
import com.system.config.WXPayConfigImpl;
import com.system.util.IPayUtil;
import com.system.util.SignUtil;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信支付
 * 
 * @author kaifa002
 *
 */
@SuppressWarnings(value = { "rawtypes", "unchecked" })
@Component
@PayTemplate(code = "nbcb")
@Slf4j
public class NBCBPayTemplate extends AbstractPayTemplate {

	public WXPay getWxPay() {
		return new WXPay(new WXPayConfigImpl());
	}

	@Override
	public ApiResult pay(Map<String, String> data) {
		log.info("使用nbcb方式支付");
		Map<String, String> resMap = new HashMap<>();
		try {
			// log.info("宁波银行下单请求报文：{}", JSONUtil.parse(data));
			log.info("宁波银行下单请求报文：{}", JSONUtil.toJsonStr(data));
			String result = IPayUtil.postData(NBCBConfig.URL, JSONUtil.toJsonStr(data), "application/json");
			log.info("宁波银行下单返回报文：{}", result);
			// 结果转成map
			// Map<String, String> respMap = new ObjectMapper().readValue(result, Map.class);
			Map<String, String> respMap = JSONUtil.toBean(result, Map.class);
			if (SignUtil.checkSign(respMap)) {
				if ("00".equals(respMap.get("return_code"))) {
					String code_url = respMap.get("url");
					QrConfig qrConfig = new QrConfig(300, 300);
					code_url = QrCodeUtil.generateAsBase64(code_url, qrConfig, "png");
					resMap.put("code_url", code_url);
					return ApiResult.build(200, "下单成功！", resMap);
				} else {
					resMap.put("qrcodeStatus", "交易失败:返回return_code是" + respMap.get("return_code") + "非00");
					return ApiResult.build(400, "下单失败！", resMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResult.build(400, "下单失败！", resMap);
	}

	@Override
	public void packageData(Map<String, String> params) {
		log.info("nbcb-packageData");
		// 设置需要的参数
		String trace_no = params.get("no");
		params.remove("no");
		params.put("trace_no", trace_no);
		params.put("mchnt_cd", NBCBConfig.MCHNT_CD);
		params.put("total_fee", "1");
		params.put("notify_url", NBCBConfig.NOTIFY_URL);
		params.put("time_out", "600");// 10 min
		params.put("tran_code", "applyQrCode");
		// 默认G2G
		String staff_id = "0002";
		String shop_id = "231015152110005001";
		String rechargeType = "10";
		if ("1".equals(rechargeType) || "2".equals(rechargeType) || "3".equals(rechargeType)) {// G2G
			staff_id = "0002";
			shop_id = "231015152110005001";
		} else if ("8".equals(rechargeType) || "9".equals(rechargeType)) {// 文化
			staff_id = "0001";
			shop_id = "231015152110005000";
		} else if ("10".equals(rechargeType) || "11".equals(rechargeType)) {// 加工
			staff_id = "0003";
			shop_id = "231015152110005002";
		}
		params.put("staff_id", staff_id);
		params.put("shop_id", shop_id);
		try {
			params.put("sign", SignUtil.generateSignature(params, NBCBConfig.PRIVATEKEY));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void signature(Map<String, String> params) throws Exception {
		boolean signVerified = true;
		// boolean signVerified = SignUtil.checkSign(params);
		// 验签失败
		if (!signVerified) {
			params.put("signature", "400");
			return;
		}
		// 查询交易
		HashMap<String, String> queryMap = new HashMap<String, String>();
		// String tradeType = "applyQrCode";
		queryMap.put("tran_code", "queryOrderStatus");
		queryMap.put("mchnt_cd", params.get("mchnt_cd"));
		queryMap.put("mchnt_cd", NBCBConfig.MCHNT_CD);
		queryMap.put("out_trade_id", params.get("out_trade_id"));
		queryMap.put("trace_no", params.get("trace_no"));
		if (StringUtils.isEmpty(params.get("trace_no"))) {
			queryMap.put("trace_no", params.get("traceNo"));
		}
		if (StringUtils.isEmpty(params.get("out_trade_id"))) {
			queryMap.put("out_trade_id", params.get("outTradeId"));
		}
		queryMap.put("sign", SignUtil.generateSignature(queryMap, NBCBConfig.PRIVATEKEY));
		String jsonString = new ObjectMapper().writeValueAsString(queryMap);//
		// 执行查询
		String result = IPayUtil.postData(NBCBConfig.URL, jsonString, "application/json");
		// Map<String, String> respMap = new ObjectMapper().readValue(result, Map.class);
		Map<String, String> resultMap = JSONUtil.toBean(result, Map.class);
		String trans_status = resultMap.get("trans_status");
		String return_code = resultMap.get("return_code");
		if (!("00".equals(return_code) && "02".equals(trans_status))) {
			params.put("signature", "400");
			return;
		}
		params.put("signature", "200");
	}

	@Override
	public String retSuccess() {
		return notifyToNBCB(200, true);
	}

	@Override
	public String retFail() {
		return notifyToNBCB(205, false);
	}

	public String notifyToNBCB(Integer return_code, boolean return_flag) {
		HashMap responseMap = new HashMap();
		responseMap.put("status", return_code);
		responseMap.put("success", return_flag);
		return JSONUtil.toJsonStr(responseMap);
	}

}
